# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from traffic.models import Tariff, TrafficCategory, TariffRule, UserProfile, \
    PrepaidPacket, Payment

def migrate():
    from django.conf import settings
    import re
    import datetime
    cre = re.compile("^(\S+)\ (\S+)\ (?:\((.+)\))?(.*)$")
    # email-ы персонала
    staff = ['kreved@admin', 'grisha@admin', 'serov@admin']
    # email-ы суперадминов
    superadmin = ['kreved@admin']
    from MySQLdb import connect
    conn = connect(host='127.0.0.1', port=3306, db=settings.MYSQL_DB, \
        user=settings.MYSQL_USERNAME, passwd=settings.MYSQL_PASSWORD, \
        charset='utf8')
    cursor = conn.cursor()
    
    # тарифы
    cursor.execute('select id, description, price, `interval`, public from tariffs')
    Tariff.objects.all().delete()
    for id, description, price, interval, public in cursor:
        t = Tariff(id=id, name=description, cost=price, period=interval/86400, \
            is_public=public)
        print t
        t.save()
    
    # типы траффика
    cursor.execute('select ID, description, public from traffic_types')
    TrafficCategory.objects.all().delete()
    for id, name, is_public in cursor:
        t = TrafficCategory(id=id, name=name, is_public=is_public)
        print t
        t.save()
    
    # правила
    cursor.execute('select tariff_id, traf_id, packet, cost from tariff_options')
    TariffRule.objects.all().delete()
    for tariff_id, traf_id, packet, cost in cursor:
        #print (tariff_id, traf_id, packet, cost)
        t = TariffRule(\
            traffic_category=TrafficCategory.objects.get(id=traf_id), \
            tariff=Tariff.objects.get(id=tariff_id), \
            packet=packet, excess_price=cost)
        print t
        t.save()
    
    # пользователи
    cursor.execute('''select id, login, mail, pass, balance, ip, status,
        regdate, comment, netuntil, lastact, tarif, lastabon, credit, sha(concat(login, PASS)) from users''')
    User.objects.all().delete()
    UserProfile.objects.all().delete()
    for id, login, mail, passwd, balance, ip, status, regdate, comment, \
        netuntil, lastact, tarif, lastabon, credit, apikey in cursor:
        last_name, first_name, address, comment = cre.search(comment).groups(u'')
        u = User(id=id, username=login, email=mail, password=passwd, \
            date_joined=regdate, is_staff=(mail in staff), \
            is_superuser=(mail in superadmin), last_name=last_name, \
            first_name=first_name)
        tariff = Tariff.objects.get(id=tarif)
        paid_until = lastabon + 86400*tariff.period
        paid_until = datetime.datetime.fromtimestamp(paid_until)
        inet_until = datetime.datetime.fromtimestamp(netuntil)
        lastact = datetime.datetime.fromtimestamp(lastact)
        #print paid_until
        p = UserProfile(user=u, address=address, comment=comment, \
            balance=balance, ip=ip.replace("192.168.0.", "192.168.8."), \
            inet=status, inet_until=inet_until, \
            last_activity=lastact, tariff=tariff, paid_until=paid_until, \
            credit=credit, blocked=(tariff.name=='Blocked'), key=apikey)
        print u, p
        u.save()
        p.save()
    
    # предоплаченные пакеты
    cursor.execute('select userid, traf_id, prepaid from prepaid_packets')
    PrepaidPacket.objects.all().delete()
    for userid, traf_id, prepaid in cursor:
        #print (tariff_id, traf_id, packet, cost)
        try:
            User.objects.get(id=userid)
        except:
            print "lost prepaid, userid=%d, traf_id=%d, prepaid=%d" % \
                (userid, traf_id, prepaid)
            continue
        t = PrepaidPacket( \
            user=User.objects.get(id=userid).get_profile(), \
            traffic_category=TrafficCategory.objects.get(id=traf_id), \
            prepaid=prepaid)
        print t
        t.save()
    PrepaidPacket.objects.filter(prepaid=0).delete()

    # история платежей
    cursor.execute('select to_id, concat(date, " ", time), s, from_id, comment from payments')
    Payment.objects.all().delete()
    for uid, time, sum, cashier, comment in cursor:
        try:
            cashier = User.objects.get(id=cashier).get_profile()
        except:
            cashier = None
        try:
            user = User.objects.get(id=uid).get_profile()
        except:
            print "lost payment, userid=%d" % (userid, )
            continue
        t = Payment(user=user, cashier=cashier, \
            date=time, sum=sum, comment=comment)
        print t
        t.save()

    for u in UserProfile.objects.all():
        u.check()
        